package com.hzit.cart.controller;

import com.hzit.cart.domain.ItemDTO;
import com.hzit.cart.interceptor.LoginInterceptor;
import com.hzit.cart.service.ICartService;
import com.ruoyi.common.core.constant.HzitConstants;
import com.ruoyi.system.api.domain.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Controller
@RequestMapping
public class CartController {

	@Autowired
	private ICartService cartService;

	//1. 添加到购物车
	@GetMapping("/cart/addCart/{id}/{num}")
	public String addCart(@PathVariable("num") Integer num,
	                      @PathVariable("id") Long id,
	                      RedirectAttributes attributes){       // RedirectAttributes: 在重定向时携带参数
		//1.1 将sku商品添加到购物车中
		cartService.addCart(num,id);
		// attributes.addAttribute("num",num);
		attributes.addAttribute("id",id);
		//1.2 添加成功后，重定向到添加购物车成功页面，避免了重复添加问题！！！
		return "redirect:http://cart.hzit.com/success";
	}
	// 添加购物车成功后的页面
	@GetMapping("/success")
	public String successCart(@RequestParam("id")  Long id, Model model){
		ItemDTO item = cartService.getItemFromRedis(id);
		model.addAttribute("item",item);
		return "success-cart";
	}
	// 得到登录用户
	public String getLogin(){
		return LoginInterceptor.loginThreadLocal.get();
	}
	//2. 列表购物车
	@GetMapping({"/","/cart.html"})
	public String index(Model model){
		//2.1 取得redis中的数据
		Map<String,List<ItemDTO>> cart = cartService.getCartInfoFromRedis2();
		model.addAttribute("cart",cart);

		return "cart";
	}
}
